package com.lean.android.ad.duration

import android.app.Activity
import android.app.Application
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.ProcessLifecycleOwner
import androidx.lifecycle.lifecycleScope
import com.lean.android.ad.duration.database.DurationDatabase
import com.lean.android.ad.duration.database.entities.PageDurationEntity
import kotlinx.coroutines.launch

internal class PageDurationDetector(
    private val database: DurationDatabase
) : Application.ActivityLifecycleCallbacks {

    companion object {
        private const val TAG = "PageDuration"
    }

    private val watcherMap = hashMapOf<String, DurationWatcher>()

    private val appScope by lazy {
        ProcessLifecycleOwner.get().lifecycleScope
    }

    private fun getOrCreateWatcher(activity: Activity): DurationWatcher {
        val pageName = activity.javaClass.name
        return watcherMap.getOrPut(pageName) {
            DurationWatcher()
        }
    }

    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
        Log.d(TAG, "onActivityCreated ${activity.javaClass.name}")

    }

    override fun onActivityStarted(activity: Activity) {
        Log.d(TAG, "onActivityStarted ${activity.javaClass.name}")
        getOrCreateWatcher(activity).start()
    }

    override fun onActivityResumed(activity: Activity) {
        Log.d(TAG, "onActivityResumed ${activity.javaClass.name}")
    }

    override fun onActivityPaused(activity: Activity) {
        Log.d(TAG, "onActivityPaused ${activity.javaClass.name}")
    }

    override fun onActivityStopped(activity: Activity) {
        Log.d(TAG, "onActivityStopped ${activity.javaClass.name}")
        getOrCreateWatcher(activity).stop { duration ->
            Log.d(TAG, "save duration ($duration ms) for page ${activity.javaClass.name}")
            saveDuration(activity, duration)
        }
    }

    private fun saveDuration(activity: Activity, duration: Long) {
        val pageName = activity.javaClass.name
        appScope.launch {
            database.getPageDurationDao().insert(
                PageDurationEntity(
                    pageName = pageName, duration = duration
                )
            )
        }
    }

    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
        Log.d(TAG, "onActivitySaveInstanceState ${activity.javaClass.name}")
    }

    override fun onActivityDestroyed(activity: Activity) {
        Log.d(TAG, "onActivityDestroyed ${activity.javaClass.name}")
    }
}